package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.content.model.qo.QueryCourseModel;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.enums.content.CourseChargeEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.controller.CourseAuditController;
import com.xuecheng.content.convert.CourseBaseConvert;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CourseMarket;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CourseMarketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    private CourseMarketService courseMarketService;

    /**
     * 分页查询课程
     *
     * @param params
     * @param model
     * @return
     */
    @Override
    public PageVO queryCourseList(PageRequestParams params, QueryCourseModel model, Long companyId) {

        //1判断分页数据 每页条数 大于0
        if (params.getPageNo() < 1) {
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }
        if (params.getPageSize() < 1) {
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }

        // 2构建查询条件对象LambdaQueryWrapper
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 课程名不为null时模糊查询
        queryWrapper.like(StringUtil.isNotBlank(model.getCourseName()),
                CourseBase::getName, model.getCourseName());
        //状态不为null时,条件查询
        queryWrapper.eq(StringUtil.isNotBlank(model.getAudiStatus()),
                CourseBase::getAuditStatus, model.getAudiStatus());
        queryWrapper.eq(!ObjectUtils.nullSafeEquals(companyId, CourseAuditController.OPERATION_FLAG), CourseBase::getCompanyId, companyId);

        // 3构建mp分页对象
        Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize());

        // 4.根据分页查询数据
        Page<CourseBase> pageResult = this.page(page, queryWrapper);

        // 5拿到分页好的records数据存放到List<CourseBase>
        List<CourseBase> records = pageResult.getRecords();
        //拿到总条数
        long total = pageResult.getTotal();

        // 6.将List<CourseBase>转换成List<CourseBaseDTO>
        List<CourseBaseDTO> baseDTOList = Collections.emptyList();
        if (!CollectionUtils.isEmpty(records)) {
            baseDTOList = CourseBaseConvert.INSTANCE.entitys2dtos(records);
        }

        // 7返回结果封装PageVo数据
        PageVO pageVO = new PageVO(baseDTOList, total, params.getPageNo(), params.getPageSize());

        return pageVO;
    }

    /**
     * 新增课程基本信息
     *
     * @param courseBaseDTO
     * @return
     */
    // 1.是否要开启事务
    //   如果是增删改操作，必须要开启事务
    @Transactional
    @Override
    public CourseBaseDTO createCourseBase(CourseBaseDTO courseBaseDTO) {

        // 2.判断关键数据
        //   有此数据才可以进行操作，一般有前端来传入
        //    来源：
        //      数据库表约束
        //       前端页面的表单说明
        //             为必填项：红星
        //         api接口文档（Yapi）
        verifyCourseMsg(courseBaseDTO);


        // 3.判断业务数据（添加没有业务数据判断）
        //   系统中存在的数据，如果数据状态有问题，当前操作要终止，一般数据来源于后端

        // 4.判断数据是否要被赋值（默认值）
        //  status：数据库已经赋值，无需操作
        //  审核状态 auditStatus：新添加的课程默认审核状态--未提交（状态码）
        courseBaseDTO.setAuditStatus(CourseAuditEnum.AUDIT_UNPAST_STATUS.getCode());


        // 5.将dto转为po数据
        //     因为mp的api只能对po数据进行操作
        CourseBase courseBase = CourseBaseConvert.INSTANCE.dto2entity(courseBaseDTO);


        // 6.保存数据并返回结果，判断结果是否成功
        // 课程基础信息
        boolean baseResult = this.save(courseBase);
        if (!baseResult) {
            throw new RuntimeException("课程基础信息保存失败");
        }
        // 课程营销信息
        CourseMarket courseMarket = new CourseMarket();
        courseMarket.setCourseId(courseBase.getId());
        courseMarket.setCharge(courseBaseDTO.getCharge());

        String charge = courseBaseDTO.getCharge();
        // 对收费课程进行数据判断
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(charge)) {
            BigDecimal price = courseBaseDTO.getPrice();
            if (ObjectUtils.isEmpty(price)) {
                throw new RuntimeException("收费课程介个不能为空");
            }
            courseMarket.setPrice(courseBaseDTO.getPrice().floatValue());
        }

        boolean marketResult = courseMarketService.save(courseMarket);
        if (!marketResult) {
            throw new RuntimeException("课程营销信息保存失败");
        }

        // 7.如果操作成功，将数据转为dto并返回
        Long id = courseBase.getId();
        CourseBaseDTO resultDTO = getLastCourseBaseDTO(courseBaseDTO, id);

        return resultDTO;
    }

    /**
     * 课程基本信息修改
     *
     * @param dto CourseBaseDTO  课程基础信息dto封装
     * @return CourseBaseDto  课程基础信息dto封装
     */
    @Override
    @Transactional
    public CourseBaseDTO modifyCourseBase(CourseBaseDTO dto) {
        // 1.判断关键数据
        //    可以使用添加的判断
        //    修改时：课程id是必须存在
        verifyCourseMsg(dto);
        Long courseBaseId = dto.getCourseBaseId();
        if (ObjectUtils.isEmpty(courseBaseId)) {
            throw new RuntimeException("修改课程id必须存在");
        }
        // 2.判断业务数据
        //    课程基础信息
        //        判断是否存在
        //        判断是否是同一家教学机构
        //        判断是否删除
        //        判断课程审核状态：未提交、审核未通过
        getCourseByLogic(dto.getCompanyId(), courseBaseId);

        //    课程营销
        CourseMarket courseMarket = getCourseMarket(courseBaseId);

        // 3.修改数据内容
        //    课程基础信息表
        //        有些内容是不容修改的：courseBaseId、companyid
        CourseBase po = CourseBaseConvert.INSTANCE.dto2entity(dto);
        // 为防止前端乱修改内容
        po.setCompanyId(null);
        po.setAuditStatus(null);
        po.setStatus(null);

        boolean baseResult = this.updateById(po);
        if (!baseResult) {
            throw new RuntimeException("课程修改失败");
        }

        //    课程营销数据表
        //        charge price
        // mp修改一张表少量数据使用 UpdateWrapper
        LambdaUpdateWrapper<CourseMarket> marketWrapper = new LambdaUpdateWrapper<>();
        marketWrapper.set(CourseMarket::getCharge, dto.getCharge());
        String charge = dto.getCharge();
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(charge)) {
            BigDecimal price = dto.getPrice();
            if (ObjectUtils.isEmpty(price)) {
                throw new RuntimeException("收费课程价格不能为空");
            }
            marketWrapper.set(CourseMarket::getPrice, dto.getPrice().floatValue());
        }
        marketWrapper.eq(CourseMarket::getCourseId, courseBaseId);
        boolean marketResult = courseMarketService.update(marketWrapper);
        if (!marketResult) {
            throw new RuntimeException("修改课程营销数据失败");
        }

        //     修改数据时要判断修改后结果

        // 4.返回前端最新的数据库的数据并封装为dto返回
        CourseBaseDTO courseBaseDTO = getLastCourseBaseDTO(dto, courseBaseId);
        return courseBaseDTO;
    }

    private void getCourseByLogic(Long companyId, Long courseBaseId) {
        CourseBase courseBase = getCourseBase(courseBaseId, companyId);

        String auditStatus = courseBase.getAuditStatus();
        if (CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)
        ) {
            throw new RuntimeException("课程审核状态异常");
        }
    }

    /**
     * 课程内容删除
     *
     * @param courseBaseId
     * @param companyId
     */
    @Transactional
    public void removeCourseBase(Long courseBaseId, Long companyId) {
        //1.判断关键数据的合法性
        if (ObjectUtils.isEmpty(courseBaseId) ||
                ObjectUtils.isEmpty(companyId)
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //2.根据Id获得课程基础信息并进行相应的判断
        getCourseByLogic(companyId, courseBaseId);

        // 3.修改课程信息状态值
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CourseBase::getStatus, CommonEnum.DELETE_FLAG.getCodeInt());
        updateWrapper.set(CourseBase::getChangeDate, LocalDateTime.now());

        updateWrapper.eq(CourseBase::getId, courseBaseId);

        boolean result = update(updateWrapper);
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }
    }

    /**
     * 根据课程id查询课程基础新信息
     *
     * @param courseBaseId Long 课程基础信息id值
     * @param companyId    Long 教学机构id值
     * @return CourseBaseDto 课程基础信息dto封装
     */
    @Override
    public CourseBaseDTO getCourseBaseById(Long courseBaseId, Long companyId) {
        // 1.判断关键数据
        //     courseBaseId  companyId
        if (ObjectUtils.isEmpty(courseBaseId) ||
                ObjectUtils.isEmpty(companyId)
        ) {
            throw new RuntimeException("传入参数和接口不匹配");
        }

        // 2.判断业务数据
        //     课程基础信息
        //         判断是否存在
        //         判断是否是同一家教学机构
        //         判断是否删除
        CourseBase courseBase = getCourseBase(courseBaseId, companyId);

        //     课程营销
        CourseMarket courseMarket = getCourseMarket(courseBaseId);
        // 3.查询数据并转为dto返回
        CourseBaseDTO courseBaseDTO = CourseBaseConvert.INSTANCE.entity2dto(courseBase);
        courseBaseDTO.setCharge(courseMarket.getCharge());
        courseBaseDTO.setPrice(new BigDecimal(courseMarket.getPrice()));
        return courseBaseDTO;
    }

    private CourseMarket getCourseMarket(Long courseBaseId) {
        // 课程营销
        LambdaQueryWrapper<CourseMarket> marketWrapper = new LambdaQueryWrapper<>();
        marketWrapper.eq(CourseMarket::getCourseId, courseBaseId);
        CourseMarket courseMarket = courseMarketService.getOne(marketWrapper);
        if (ObjectUtils.isEmpty(courseMarket)) {
            throw new RuntimeException("课程营销数据不存在");
        }
        return courseMarket;
    }

    private CourseBase getCourseBase(Long courseBaseId, Long companyId) {
        LambdaQueryWrapper<CourseBase> baseWrapper = new LambdaQueryWrapper<>();
        baseWrapper.eq(CourseBase::getId, courseBaseId);
        baseWrapper.eq(CourseBase::getCompanyId, companyId);
        CourseBase courseBase = this.getOne(baseWrapper);
        if (ObjectUtils.isEmpty(courseBase)) {
            throw new RuntimeException("课程不存在");
        }
        Integer status = courseBase.getStatus();
        if (!(CommonEnum.USING_FLAG.getCodeInt().equals(status))) {
            throw new RuntimeException("课程信息已被删除");
        }
        return courseBase;
    }

    private void verifyCourseMsg(CourseBaseDTO courseBaseDTO) {
        if (ObjectUtils.isEmpty(courseBaseDTO.getCompanyId())) {
            ExceptionCast.cast(ContentErrorCode.E_120018);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getName())) {
            ExceptionCast.cast(ContentErrorCode.E_120004);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getMt())) {
            ExceptionCast.cast(ContentErrorCode.E_120002);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getSt())) {
            ExceptionCast.cast(ContentErrorCode.E_120003);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getGrade())) {
            ExceptionCast.cast(ContentErrorCode.E_120007);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getTeachmode())) {
            ExceptionCast.cast(ContentErrorCode.E_120006);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getUsers())) {
            ExceptionCast.cast(ContentErrorCode.E_120019);
        }
        if (StringUtil.isEmpty(courseBaseDTO.getCharge())) {
            ExceptionCast.cast(ContentErrorCode.E_120020);
        }
    }

    private CourseBaseDTO getLastCourseBaseDTO(CourseBaseDTO dto, Long id) {
        CourseBase po = this.getById(id);

        CourseBaseDTO resultDTO = CourseBaseConvert.INSTANCE.entity2dto(po);
        resultDTO.setCharge(dto.getCharge());
        resultDTO.setPrice(dto.getPrice());
        return resultDTO;
    }

    /**
     * 课程提交
     *
     * @param courseBaseId
     * @param companyId
     */
    @Override
    @Transactional
    public void commitCourseBase(Long courseBaseId, Long companyId) {

        // 业务分析：
        //  1.判断关键数据
        if (ObjectUtils.isEmpty(courseBaseId) ||
                ObjectUtils.isEmpty(companyId)
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //  2.判断业务数据
        //      课程基础信息
        //          判断是否存在
        //          判断是否是同一家教学机构
        //          判断是否删除
        //          判断审核状态
        getCourseByLogic(companyId, courseBaseId);

        //  3.修改课程审核状态
        //      已提交
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CourseBase::getAuditStatus, CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode());
        // updateWrapper    ******会将mp自动填充失效*****
        updateWrapper.set(CourseBase::getChangeDate, LocalDateTime.now());
        updateWrapper.eq(CourseBase::getId, courseBaseId);
        boolean result = this.update(updateWrapper);
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }
    }

    @Transactional
    public void approveCourse(CourseBaseDTO dto) {
        // 业务分析：
        //  1.判断关键数据
        //      auditMind意见  auditStatus审核状态  courseid

        if (StringUtil.isEmpty(dto.getAuditMind()) ||
                StringUtil.isEmpty(dto.getAuditStatus()) ||
                ObjectUtils.isEmpty(dto.getCourseBaseId())
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //  2.判断业务数据
        //      课程基础信息
        //          判断是否存在
        //          判断是否删除
        //          判断审核状态
        //              必须为：已提交
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getId, dto.getCourseBaseId());
        queryWrapper.eq(CourseBase::getStatus, CommonEnum.USING_FLAG.getCodeInt());
        queryWrapper.eq(CourseBase::getAuditStatus, CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode());

        int count = this.count(queryWrapper);
        if (count < 1) {
            ExceptionCast.cast(ContentErrorCode.E_120023);
        }

        //      审核状态
        //          运营平台只能给课程审核状态赋值：审核通过、审核未通过
        String auditStatus = dto.getAuditStatus();
        if (CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_UNPAST_STATUS.getCode().equals(auditStatus)
        ) {
            ExceptionCast.cast(ContentErrorCode.E_120016);
        }

        //  3.修改课程审核信息
        //      auditMind意见  auditStatus审核状态  auditNum（每次+1）

        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CourseBase::getAuditStatus, dto.getAuditStatus());
        updateWrapper.set(CourseBase::getAuditMind, dto.getAuditMind());
        updateWrapper.set(CourseBase::getChangeDate, LocalDateTime.now());

        updateWrapper.eq(CourseBase::getId, dto.getCourseBaseId());
        boolean result = this.update(updateWrapper);

        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }

    }
}
